<template>
  <div class="crm-page customer-add-page">
    <div class="page-header">{{ title }}回款单</div>
    <div class="page-content transparent">
      <div class="page-card">
        <div class="card-title">
          <el-button class="back-btn" size="medium" type="text" icon="el-icon-back" @click="goMainBack()">返回</el-button>
        </div>
        <el-form ref="form" :model="form" label-width="140px" :rules="rules">

          <div class="page-card-content">
            <div class="item-title" style="margin-top:20px">
              基本信息
            </div>
            <div class="card-item">
              <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="回款单号" prop="no">
                    <el-input v-model="form.no" placeholder="根据规则自动生成" disabled maxlength="50" />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="客户名" prop="customerId">
                    <VbSelect v-model="form.customerId" :name="form.customerName" style="width:100%" :load-data="loadCustomerData" />
                  </el-form-item>
                </el-col>
                <!-- <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="单据状态" prop="status">
                    <el-select v-model="form.status" disabled style="width:100%">
                      <el-option v-for="cs in paymentStatus" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col> -->
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="所有人" prop="owner">
                    <el-input v-model="form.owner" placeholder="" maxlength="50" disabled readonly />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="合同编号" prop="contractId">
                    <VbSelect v-model="form.contractId" :name="form.contractNum" style="width:100%" :load-data="loadContractData" @change="handleContract" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="合同金额（元）" prop="contractAmount">
                    <el-input v-model="form.contractAmount" disabled placeholder="请输入合同金额" maxlength="12" />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="回款日期" prop="paymentDate">
                    <el-date-picker
                      v-model="form.paymentDate"
                      style="width:100%"
                      type="date"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="回款总金额（元）" prop="amount">
                    <el-input v-model="totalAmount" disabled placeholder="请输入报价金额" maxlength="12" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="付款方式" prop="paymentMode">
                    <el-select v-model="form.paymentMode" style="width:100%">
                      <el-option v-for="cs in payMethods" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" :rows="5" placeholder="请输入备注" maxlength="255" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <div class="page-card-content">
            <div class="item-title" style="margin-top:20px">
              添加明细
            </div>

            <div class="card-item" style="display: flex;justify-content: space-between;align-items: center;">
              <div style="color:#666;font-size:12px">已添加数据条数（{{ form.list.length }}）条</div>
              <el-button type="primary" @click="addTableRow('list')">添加</el-button>
            </div>
            <el-form-item prop="" label-width="0">
              <div class="card-item" style="padding-top:5px">
                <el-table
                  border
                  :data="form.list"
                >
                  <el-table-column label="项目/订单编号">
                    <template slot-scope="{row,$index}">
                      <el-form-item>
                        <VbSelect v-model="row.orderId" :name="row.orderNo" style="width:100%" :load-data="loadOrderData" @change="(v)=>{handleChangeOrder(v,$index)}" />
                        <!-- <el-input v-model="row.orderNo" placeholder="订单号" /> -->
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="订单金额（元）">
                    <template slot-scope="{row}">
                      <el-input v-model="row.orderAmount" v-checkMoney disabled class="num-input" placeholder="订单金额" />
                    </template>
                  </el-table-column>
                  <el-table-column label="回款计划编号">
                    <template slot-scope="{row}">
                      <el-form-item>
                        <el-input v-model="row.paymentPlanNo" placeholder="回款计划编号" maxlength="20" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="计划回款日期">
                    <template slot-scope="{row}">

                      <el-date-picker
                        v-model="row.paymentPlaneDate"
                        style="width:100%"
                        type="date"
                        placeholder="选择日期"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="计划回款金额（元）">
                    <template slot-scope="{row}">
                      <el-input v-model="row.paymentPlaneAmount" v-checkMoney class="num-input" placeholder="计划回款金额" />
                    </template>
                  </el-table-column>
                  <el-table-column label="本次回款金额">
                    <template slot="header">
                      <span class="is-required-cloum">本次回款金额（元）</span>
                    </template>
                    <template slot-scope="{row,$index}">
                      <el-form-item
                        :prop="`list[${$index}].amount`"
                        :rules="rules.num"
                      >
                        <el-input v-model="row.amount" placeholder="本次回款金额" class="num-input" maxlength="11" />
                        <div slot="error" slot-scope="scope" class="cus-item-error">
                          {{ scope.error }}
                        </div>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column
                    label="剩余金额（元）"
                  >
                    <template slot-scope="{row,$index}">
                      <el-form-item
                        :prop="`list[${$index}].surplusAmount`"
                        :rules="[ { validator: validateSurplusAmount, trigger: ['blur', 'change'] }]"
                      >
                        <el-input v-model="row.surplusAmount" v-checkMoney disabled class="num-input" placeholder="剩余金额" />
                        <div slot="error" slot-scope="scope" class="cus-item-error">
                          {{ scope.error }}
                        </div>
                      </el-form-item>
                    </template>
                  </el-table-column> -->
                  <el-table-column label="备注">
                    <template slot-scope="{row}">
                      <el-input v-model="row.remark" placeholder="备注" style="width:100%" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"

                    fixed="right"
                    width="100"

                    class-name="table-opt-col"
                  >
                    <template slot-scope="{row,$index}">
                      <el-button type="text" @click="handleDelete(row,$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form-item>
          </div>
          <div class="page-card-content" style="padding-top:20px">
            <el-row style="text-align:right">
              <el-button plain @click="handleClose">取消</el-button>
              <el-button type="primary" @click="submitForm">保存</el-button>
            </el-row>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>

import BigNumber from 'bignumber.js'
import { getCustomerSelect } from '@/api/customer'
import { getContractSelect, getContract } from '@/api/contract'
import { getPay, savePay, updatePay } from '@/api/pay'
import { getOrderSelect, getOrder } from '@/api/order'
import { paymentStatus, payMethods } from '@/utils/enums'
import { formatTime } from '@/utils/tools'
import dayjs from 'dayjs'
export default {
  name: 'CustomerAdd',
  components: { },
  data() {
    const validateNum = (rule, value, callback) => {
      const num = new BigNumber(value)
      if (num.isNaN()) {
        callback(new Error('必须是数字'))
      } else if (num.comparedTo(0) <= 0) {
        callback(new Error('数字必须大于0'))
      } else {
        callback()
      }
    }
    const validateList = (rule, value, callback) => {
      if (value && value.length > 0) {
        callback()
      } else {
        callback(new Error('必须填写明细'))
      }
    }
    return {
      paymentStatus,
      payMethods,
      billList: [],
      receiveList: [],
      invoiceListSelects: [],
      receiveListSelects: [],
      form: {
        'amount': '',
        'contractId': '',
        'contractNum': '',
        contractAmount: '',
        'customerId': '',
        'list': [],
        'paymentDate': dayjs(),
        'paymentMode': 2,
        'remark': '',
        'status': 1,
        owner: ''

      },
      rules: {
        contractId: [
          { required: true, message: '合同编号不能为空', trigger: ['blur', 'change'] }
        ],
        customerId: [
          { required: true, message: '客户名不能为空', trigger: ['blur', 'change'] }
        ],
        list: [
          { validator: validateList, trigger: ['blur', 'change'] }
        ],
        num: [
          { validator: validateNum, trigger: ['blur', 'change'] }
        ],
        paymentDate: [{ required: true, message: '回款日期不能为空', trigger: ['blur', 'change'] }]

      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '修改' : '新增'
    },
    totalAmount() {
      return this.form.list.map(m => m.amount).reduce(function(prev, cur, index, arr) {
        console.log(prev, cur, index)
        return BigNumber(prev || 0).plus(cur || 0).toFixed(2)
      }, 0)
    }

  },
  // watch: {
  //   'form.list': {
  //     handler(newList) {
  //       // 循环遍历
  //       const orders = {}
  //       newList.forEach(m => {
  //         orders[m.orderId] = m.orderAmount
  //       })
  //       newList.forEach(item => {
  //         // 计算当前行的剩余金额
  //         if (item.orderId && item.orderAmount && item.amount > 0) {
  //           item.surplusAmount = BigNumber(orders[item.orderId]).minus(item.amount).toFixed(2)
  //           orders[item.orderId] = BigNumber(orders[item.orderId]).minus(item.amount)
  //         }
  //       })
  //     },
  //     deep: true,
  //     immediate: true
  //   }

  // },
  mounted() {
    const id = this.$route.query.id
    if (id) {
      getPay({ id }).then(res => {
        this.form = res
      })
    } else {
      this.form.owner = this.USER.userName
      const customerId = this.$route.query.customerId
      const customerName = this.$route.query.customerName
      if (customerId && customerName) {
        this.form.customerId = customerId
        this.form.customerName = customerName
      }
      const contractId = this.$route.query.contractId
      const contractNo = this.$route.query.contractNo
      if (contractId && contractNo) {
        this.form.contractId = contractId
        this.form.contractNum = contractNo
        this.handleContract({ id: contractId })
      }
    }
  },
  methods: {
    formatTime,
    validateSurplusAmount(rule, value, callback) {
      if (value >= 0) {
        callback()
      } else {
        callback(new Error('金额不能小于0'))
      }
    },
    loadCustomerData(params) {
      return getCustomerSelect(params).then(res => {
        return res
      })
    },
    loadContractData(params) {
      return getContractSelect(params).then(res => {
        return res
      })
    },
    loadOrderData(params) {
      return getOrderSelect(params).then(res => {
        return res
      })
    },
    handleChangeOrder(v, i) {
      getOrder({ id: v.id }).then(res => {
        this.form.list[i].orderAmount = BigNumber(res.amount).toFixed(2)
        this.form.list[i].orderNo = res.no
      })
    },
    handleClose() {
      this.$router.back()
    },

    handleDelete(row, i) {
      // 111
      console.log('1111:', i)
      this.form.list.splice(i, 1)
    },
    addTableRow(t) {
      this.form[t].push({
        'orderId': '',
        'orderNo': '',
        orderAmount: '',
        amount: '',
        'paymentPlanId': '',
        'paymentPlanNo': '',
        'paymentPlaneAmount': '',
        'paymentPlaneDate': '',
        'surplusAmount': ''
      })
    },
    handleContract(v) {
      getContract({ id: v.id }).then(res => {
        this.form.contractAmount = new BigNumber(res.amount).toFixed(2)
        this.form.contractNum = res.number
      })
    },

    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.amount = this.totalAmount
          // 有id 是修改
          if (this.form.id) {
            updatePay(this.form).then(res => {
              console.log('updateQuote:', res)
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.$router.back(-1)
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '修改失败'
              })
            })
          } else {
            savePay(this.form).then(res => {
              this.$message({
                type: 'success',
                message: '新增成功'
              })
              this.$router.back(-1)
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '新增失败'
              })
            })
          }
        }
      })
    }

  }
}
</script>
<style lang="scss">
.customer-add-page{
    .el-form-item--small.el-form-item{
      margin-bottom: 0;
    }
    .num-input.el-input--small .el-input__inner{
      text-align: right;
    }

}

</style>

